package cn.supermaster.management.web.service.tool.impl;

import cn.supermaster.management.common.entity.CxSelect;
import cn.supermaster.management.common.page.TableDataInfo;
import cn.supermaster.management.common.response.WebResponse;
import cn.supermaster.management.common.text.Convert;
import cn.supermaster.management.common.utils.TextUtils;
import cn.supermaster.management.common.utils.WebHelper;
import cn.supermaster.management.common.utils.security.PermissionUtils;
import cn.supermaster.management.tool.domain.GenTable;
import cn.supermaster.management.tool.domain.GenTableColumn;
import cn.supermaster.management.tool.service.IGenTableColumnService;
import cn.supermaster.management.tool.service.IGenTableService;
import cn.supermaster.management.web.service.tool.IGenService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * All rights Reserved, Designed By www.super-bytecode.com
 *
 * @ProjectName: supermaster-management
 * @Package: cn.supermaster.management.web.service.tool.impl
 * @ClassName: GenServiceImpl
 * @Description: []
 * <p> </p>
 * @Author: [Lance Ting]
 * @Date: 2021/1/13 20:03
 * @Version: V1.0
 * @Copyright: 2021 www.super-bytecode.com Inc. All rights reserved.
 * TODO: 注意,本文件Lance Ting所作,如果转载或使用请标明具体出处!
 **/
@Service
public class GenServiceImpl implements IGenService {
    private String prefix = "tool/gen";

    @Autowired
    private IGenTableService genTableService;

    @Autowired
    private IGenTableColumnService genTableColumnService;

    /*
     * ================================================
     *  页面跳转功能实现
     * ================================================
     */

    /**
     * @description: [跳转到代码生成器首页界面]
     * <p></P>
     * @title: skipGenIndexHtml
     * @author: Lance Ting
     * @date: 2021-01-13
     * @return: java.lang.String
     */
    @Override
    public String skipGenIndexHtml() {
        return prefix + "/gen";
    }

    /**
     * @description: [跳转导入表结构界面]
     * <p></P>
     * @title: skipImportTableHtml
     * @author: Lance Ting
     * @date: 2021-01-13
     * @return: java.lang.String
     */
    @Override
    public String skipImportTableHtml() {
        return prefix + "/importTable";
    }

    /**
     * @description: [跳转修改代码生成业务界面]
     * <p></P>
     * @title: skipModifyGenHtml
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: modelMap
     * @Param: tableId
     * @return: java.lang.String
     */
    @Override
    public String skipModifyGenHtml(ModelMap modelMap, Long tableId) {
        GenTable table = genTableService.selectGenTableById(tableId);
        List<GenTable> genTables = genTableService.selectGenTableAll();
        List<CxSelect> cxSelect = new ArrayList<CxSelect>();
        // 设置table信息
        for (GenTable genTable : genTables) {
            CxSelect cx = getCxSelect(table.getTableName(), genTable);
            if (cx == null) continue;
            cxSelect.add(cx);
        }
        modelMap.put("table", table);
        modelMap.put("data", JSONObject.toJSON(cxSelect));
        return prefix + "/edit";
    }

    /*
     * ================================================
     *  Rest功能实现
     * ================================================
     */

    /**
     * @param genTable
     * @description: [查询代码生成列表]
     * <p></P>
     * @title: queryGenListByCondition
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: genTable
     * @return: cn.supermaster.management.common.page.TableDataInfo
     */
    @Override
    public TableDataInfo queryGenListByCondition(GenTable genTable) {
        WebHelper.startPage();
        List<GenTable> list = genTableService.selectGenTableList(genTable);
        return WebHelper.getDataTable(list);
    }

    /***
     * @description: [查询数据库列表]
     * <p></P>
     * @title: queryTableListByCondition
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: genTable
     * @return: cn.supermaster.management.common.page.TableDataInfo
     * @param genTable
     */
    @Override
    public TableDataInfo queryTableListByCondition(GenTable genTable) {
        WebHelper.startPage();
        List<GenTable> list = genTableService.selectDbTableList(genTable);
        return WebHelper.getDataTable(list);
    }

    /***
     * @description: [查询数据表字段列表]
     * <p></P>
     * @title: queryColumnListByCondition
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: genTableColumn
     * @return: cn.supermaster.management.common.page.TableDataInfo
     * @throws:
     * @param genTableColumn
     */
    @Override
    public TableDataInfo queryColumnListByCondition(GenTableColumn genTableColumn) {
        TableDataInfo dataInfo = new TableDataInfo();
        List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(genTableColumn);
        dataInfo.setRows(list);
        dataInfo.setTotal(list.size());
        return dataInfo;
    }

    /**
     * @description: [导入表结构（保存）]
     * <p></P>
     * @title: doImportTable2Db
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: tables
     * @return: cn.supermaster.management.common.response.WebResult
     * @throws:
     */
    @Override
    public WebResponse doImportTable2Db(String tables) {
        String[] tableNames = Convert.toStrArray(tables);
        // 查询表信息
        List<GenTable> tableList = genTableService.selectDbTableListByNames(tableNames);
        String operName = (String) PermissionUtils.getPrincipalProperty("userName");
        genTableService.importGenTable(tableList, operName);
        return WebResponse.success();
    }

    /***
     * @description: [修改代码生成业务]
     * <p></P>
     * @title: doModifyGenTable
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: genTable
     * @return: cn.supermaster.management.common.response.WebResult
     * @param genTable
     */
    @Override
    public WebResponse doModifyGenTable(GenTable genTable) {
        genTableService.validateEdit(genTable);
        genTableService.updateGenTable(genTable);
        return WebResponse.success();
    }

    /**
     * @param ids
     * @description: [删除table]
     * <p></P>
     * @title: doRemoveGenTable
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: ids
     * @return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doRemoveGenTable(String ids) {
        genTableService.deleteGenTableByIds(ids);
        return WebResponse.success();
    }

    /**
     * @param tableId
     * @description: [ 预览代码]
     * <p></P>
     * @title: doCodePreview
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: tableId
     * @return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doCodePreview(Long tableId) {
        Map<String, String> dataMap = genTableService.previewCode(tableId);
        return WebResponse.success(dataMap);
    }

    /***
     * @description: [生成代码（下载方式）]
     * <p></P>
     * @title: doDownloadCodeWithZip
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: response
     * @Param: tableName
     * @return: void
     */
    @Override
    public void doDownloadCodeWithZip(HttpServletResponse response, String tableName) {
        try {
            byte[] data = genTableService.downloadCode(tableName);
            buildCodeWithZip(response, data);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param tableName
     * @description: []
     * <p></P>
     * @title: doBuildCode
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: tableName
     * @return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doBuildCode(String tableName) {

        genTableService.generatorCode(tableName);
        return WebResponse.success();
    }

    /**
     * @param tableName
     * @description: [同步数据库]
     * <p></P>
     * @title: doSnchDatebase
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: tableName
     * @return: cn.supermaster.management.common.response.WebResult
     */
    @Override
    public WebResponse doSnchDatebase(String tableName) {
        genTableService.synchDb(tableName);
        return WebResponse.success();
    }

    /**
     * @param response
     * @param tables
     * @description: [批量生成代码]
     * <p></P>
     * @title: doBatchBuildCode
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: response
     * @Param: tables
     * @return: void
     * @throws:
     */
    @Override
    public void doBatchBuildCode(HttpServletResponse response, String tables) {
        try {
            String[] tableNames = Convert.toStrArray(tables);
            byte[] data = genTableService.downloadCode(tableNames);
            buildCodeWithZip(response, data);
        } catch (Exception e) {
        }
    }

    /*
     * ================================================
     *  通用功能实现
     * ================================================
     */

    /**
     * @description: [获取子集数据字段]
     * <p></P>
     * @title: getCxSelect
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: tableName
     * @Param: genTable
     * @return: cn.supermaster.management.common.entity.CxSelect
     */
    private CxSelect getCxSelect(String tableName, GenTable genTable) {
        CxSelect cxTable = null;
        if (TextUtils.equals(tableName, genTable.getTableName())) return null;
        //
        String selectTableName = genTable.getTableName();
        String tableComment = genTable.getTableComment();
        cxTable = new CxSelect(selectTableName, selectTableName + '：' + tableComment);
        List<CxSelect> cxColumns = new ArrayList<CxSelect>();
        for (GenTableColumn tableColumn : genTable.getColumns()) {
            String columnName = tableColumn.getColumnName();
            String columnComment = tableColumn.getColumnComment();
            cxColumns.add(new CxSelect(columnName, columnName + '：' + columnComment));
        }
        cxTable.setS(cxColumns);
        return cxTable;
    }

    /**
     * @description: [生成zip文件]
     * <p></P>
     * @title: genCode
     * @author: Lance Ting
     * @date: 2021-01-13
     * @param: response
     * @Param: data
     * @return: void
     */
    private void buildCodeWithZip(HttpServletResponse response, byte[] data) throws IOException {
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"supermaster-management.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
    }
}